package com.mijie.homi.admin.web.user;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.mijie.core.Paging;
import com.mijie.homi.admin.domain.commom.OperationsStat;
import com.mijie.homi.admin.domain.user.Account;
import com.mijie.homi.admin.domain.user.InternalUser;
import com.mijie.homi.admin.service.commom.StatService;
import com.mijie.homi.admin.service.message.MessageService;
import com.mijie.homi.admin.service.notify.NotifyUserAgent;
import com.mijie.homi.admin.service.user.GradeService;
import com.mijie.homi.admin.service.user.UserExtInfoService;
import com.mijie.homi.admin.service.user.UserService;
import com.mijie.homi.common.domain.Grade;
import com.mijie.homi.common.domain.SystemMessage;
import com.mijie.homi.common.domain.user.DeviceInfo;
import com.mijie.util.GeoUtil;
import com.mijie.util.Helper;
import com.mijie.util.IOUtil;

@SuppressWarnings("unchecked")
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	@Autowired
	private UserExtInfoService extInfoService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private NotifyUserAgent notifyUserAgent;
	@Autowired
	private GradeService gradeService;
	@Autowired
	private StatService statService;
	
	private static Logger logger  = Logger.getLogger(UserController.class);
	
	@RequestMapping("/list")
	public String list(Paging<Account> paging,Model model,HttpServletRequest request){
		Map<String,Object> searchBundle = (Map<String, Object>) request.getAttribute("searchBundle");
		if(searchBundle.containsKey("grade")){
			Integer[] integralRange = gradeService.getIntegralRangeByGrade(Integer.parseInt((String) searchBundle.get("grade")));
			if(integralRange!=null){
				searchBundle.put("minIntegral", integralRange[0]);
				searchBundle.put("maxIntegral", integralRange[1]);
			}
		}
		if(searchBundle.containsKey("account")){
			String account = (String) searchBundle.get("account");
			account = account.trim();
			if(!account.isEmpty()){
				if(Helper.isEmail(account)) searchBundle.put("email", account);
				else if(Helper.isInt(account)) searchBundle.put("id", Integer.parseInt(account));
				else searchBundle.put("nickName", account);
			}
		}
		userService.listAccount(paging, searchBundle);
		Integer numOfUser = userService.countRegisterUser();
		Integer onlineTotalTime = userService.getOnlineTotalTime();
		String avgOnlineTime = new java.text.DecimalFormat("#.##").format(onlineTotalTime/numOfUser/60.0);
		List<Grade> gradeList = gradeService.listGrade();
		model.addAttribute("onlineUserAmount",userService.getOnlineUserAmount());
		model.addAttribute("maxOnlineUserAmount",userService.getMaxOnlineUserAmount());
		String maxOnlineStatAt = userService.getMaxOnlineStatAt();
		model.addAttribute("maxOnlineStatAt",maxOnlineStatAt==null?"未来":maxOnlineStatAt);
		model.addAttribute("numOfUser",numOfUser);
		model.addAttribute("avgOnlineTime",avgOnlineTime);
		model.addAttribute("gradeList",gradeList);
		model.addAllAttributes(searchBundle);
		return "user/list";
	}
	
	@RequestMapping("/internal/active")
	public void activeInternalUser(int userId,HttpServletResponse response) throws IOException {
		InternalUser internalUser = userService.getFreeInternalUser(userId);
		if(internalUser==null){
			IOUtil.write(response, "马甲已被使用");
		}else{
			String nickName;
			try {
				nickName = userService.activeInternalUser(internalUser);
				if(nickName!=null){
					IOUtil.write(response, "激活成功，马甲昵称:"+nickName);
				}else{
					IOUtil.write(response, "激活失败");
				}
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				IOUtil.write(response, "激活中出现异常");
			}
		}
	}
	
	@RequestMapping("/operationsStat")
	public String operationsStat(Paging<OperationsStat> paging,Model model,HttpServletRequest request){
		Map<String,Object> searchBundle = (Map<String, Object>) request.getAttribute("searchBundle");
		if(!searchBundle.containsKey("operationsStatType")) searchBundle.put("operationsStatType", "dayRetain");
		
		String operationsStatType = (String) searchBundle.get("operationsStatType");
		if(operationsStatType.startsWith("day")){
			searchBundle.put("tableName", "statByDay");
		}else if(operationsStatType.startsWith("week")){
			searchBundle.put("tableName", "statByWeek");
		}else if(operationsStatType.startsWith("month")){
			searchBundle.put("tableName", "statByMonth");
		}
		if(operationsStatType.endsWith("Active")) searchBundle.put("statActiveUser", true);
		statService.listOperationsStat(paging, searchBundle);
		model.addAllAttributes(searchBundle);
		model.addAttribute("avg", statService.getOperationsStatAvg(searchBundle));
		return "user/operationsStat";
	}
	
	@RequestMapping("/internal/list")
	public String internalUserList(Paging<InternalUser> paging,Model model,HttpServletRequest request){
		Map<String,Object> searchBundle = (Map<String, Object>) request.getAttribute("searchBundle");
		userService.getInternalUserPage(paging,searchBundle);
		model.addAllAttributes(searchBundle);
		return "user/internal/list";
	}
	
	@RequestMapping("/internal/passwd_save")
	public void internalUserSetPasswd(int id,String passwd,HttpServletResponse response) 
			throws IOException{
		int rows = userService.updateInternalUserPasswd(id, passwd);
		if(rows==0) IOUtil.write(response, "修改密码失败");
		else  IOUtil.write(response, "修改密码成功，新密码:"+passwd);
	}
	
	@RequestMapping("/internal/setPasswd")
	public String setPasswd(int id,String passwd,Model model){
		model.addAttribute("passwd", passwd);
		model.addAttribute("id", id);
		return "user/setPasswd";
	}
	
	
	@RequestMapping("/changeGender")
	public void changeGender(int id,int gender,HttpServletResponse response) throws IOException{
		try {
			this.userService.setGender(id, gender);
		} catch (Exception e) {
			IOUtil.write(response,"error");
		}
	}
	
	@RequestMapping("/reset_passwd")
	public String resetPasswd(int id,HttpServletRequest request){
		userService.resetPasswd(id);
		return "redirect:/user/list.shtml";
	}
	
	
	@RequestMapping("/device/info")
	public String getDeviceInfo(String deviceId,double longitude,double latitude,String ip,Model model){
		DeviceInfo deviceInfo = userService.getDeviceInfo(deviceId);
		model.addAttribute("deviceInfo", deviceInfo);
		StringBuilder address  = new StringBuilder();
		String addr = GeoUtil.getAddress(longitude, latitude);
		if(addr!=null){
			address.append(addr);
		}else if(ip!=null && !ip.trim().isEmpty()){
			String[] region = GeoUtil.getProvinceAndCity(ip);
			if(region!=null) address.append(region[0]).append(" ").append(region[1]);
		}
		model.addAttribute("address", address==null?"未知":address);
		return "user/deviceInfo";
	}
	
	@RequestMapping("/block")
	public String block(int id) throws Exception{
		userService.block(id,0);
		return "redirect:/user/list.shtml";
	}
	
	@RequestMapping("/unblock")
	public String unblock(int id) throws Exception{
		userService.unblock(id);
		return "redirect:/user/list.shtml";
	}
	
	@RequestMapping("/setIntegral")
	public String setIntegral(int id,Model model){
		int integral = extInfoService.getIntegralByUserId(id);
		model.addAttribute("integral", integral);
		model.addAttribute("id", id);
		return "user/setIntegral";
	}
	
	@RequestMapping("/saveIntegral")
	public void updateIntegral(int id,int integral){
		extInfoService.updateIntegral(id,integral);
	}
	
	@RequestMapping("/verify/reject")
	public String rejectVerify(int id){
		userService.rejectVerify(id);
		return "redirect:/user/verify/list.shtml";
	}
	
	
	@RequestMapping("/pushById")
	public void  pushById(String ids,SystemMessage msg,HttpServletResponse response) throws IOException {
		if(msg.getLinkName()==null) msg.setLinkName("");
		if(msg.getLink()==null) msg.setLink("");
		msg.setCreateAt(new Date());
		//int id = messageService.createSystemMessage(msg);
		logger.info(msg.toString());
		//if(id>0){
			String[] idBuff = ids.split(",");
			if(idBuff!=null){
				for(String userId : idBuff){
					if(!userId.trim().isEmpty()){
						try{
							notifyUserAgent.sendSystemMessage(Integer.parseInt(userId.trim()), msg);
						}catch(Exception e){
							continue;
						}
					}
						
				}
				IOUtil.write(response, "true");
			}else{
				logger.info("没选择用户");
				IOUtil.write(response, "false");
			}
		//}else{
			//IOUtil.write(response, "false");
		//}
	}
	
	@RequestMapping("/pushToAll")
	public void pushToAll(SystemMessage msg,HttpServletResponse response) throws IOException{
		if(msg.getLinkName()==null) msg.setLinkName("");
		if(msg.getLink()==null) msg.setLink("");
		msg.setCreateAt(new Date());
		int id = messageService.createSystemMessage(msg);
		logger.info(msg.toString());
		if(id>0){
//			int offset = 0;
//			int limit = 100;
//			List<Integer> list = null;
//			while(true){
//				list = userService.listUserId(offset, limit);
//				if(list!=null && !list.isEmpty()){
//					offset += limit;
//					for(int userId : list){
						notifyUserAgent.sendSystemMessage(-1, msg);
//					}
//				}else{
//					break;
//				}
//			}
		}
		IOUtil.write(response, "true");
	}
	
}
